package MetroMessenger;

import java.io.IOException;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.DatagramPacket;
import java.net.SocketTimeoutException;

public class PacketReceiver implements Runnable 
{
   private MessageListener messageListener; 
   private MulticastSocket multicastSocket; 
   private InetAddress multicastGroup;
   private boolean keepListening = true;
   
   public PacketReceiver( MessageListener listener ) 
   {
      messageListener = listener; 
      
      try 
      {
         multicastSocket = new MulticastSocket( SocketMessengerConstants.MULTICAST_LISTENING_PORT );
         multicastGroup = InetAddress.getByName( SocketMessengerConstants.MULTICAST_ADDRESS );
         multicastSocket.joinGroup( multicastGroup ); 
         multicastSocket.setSoTimeout( 5000 );
      } 
      catch ( IOException ioException ) 
      {
         ioException.printStackTrace();
      } 
   }
   public void run() 
   {          
      while ( keepListening ) 
      {
         byte[] buffer = new byte[ SocketMessengerConstants.MESSAGE_SIZE ];
         DatagramPacket packet = new DatagramPacket( buffer, SocketMessengerConstants.MESSAGE_SIZE );

         try 
         {            
            multicastSocket.receive( packet ); 
         }
         catch ( SocketTimeoutException socketTimeoutException ) 
         {
            continue;
         }
         catch ( IOException ioException ) 
         {
            ioException.printStackTrace();
            break;
         }
         
         String message = new String( packet.getData() );
         message = message.trim(); 
         messageListener.messageReceived(message);
      }

      try 
      {
         multicastSocket.leaveGroup( multicastGroup ); 
         multicastSocket.close();
      } 
      catch ( IOException ioException )
      { 
         ioException.printStackTrace();
      }
   }
   public void stopListening() 
   {
      keepListening = false;
   }
}